

var threeSum = function(nums) {
  const length = nums.length;
  const res = [];
  nums.sort((a,b)=>a-b);
  for(let i = 0; i<length; i++) {
      if(i>0 && nums[i]===nums[i-1]) continue;
      let left = i+1;
      let right = length-1;
      while(left<right) {
          const sum = nums[i] + nums[left] + nums[right];
          if(sum === 0) {
              res.push([nums[i],nums[left],nums[right]])
              left++;
              while(nums[left] === nums[left-1]){
                  left++;
              }
              
          }else if(sum > 0) {
              right--;
          }else{
              left++;
          }
      }
  }
  return res;
};
console.log(threeSum([-1,0,1,2,-1,-4])); 